const scopeMap = {
  "userLocation": '精确地理位置'
}
let key = ""
/**
 * 是否授权
 * @param {*} scope  scope列表 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/AuthSetting.html
 */
export default function wxAuth(scope) {
  key = 'scope.' + scope
  return new Promise((resolve, reject) => {
    if (scope === 'userLocation') {
      const { locationEnabled } = wx.getSystemSetting()
      if (!locationEnabled) {
        wx.showToast({
          title: '请打开手机定位！',
          icon: 'none'
        })
        return
      }
    }
    wx.getSetting({
      success(res) {
        const { authSetting } = res
        const isAuth = authSetting[key]
        if (isAuth) {
          resolve({ isAuth })
        } else {
          authorize(scope, resolve, reject)
        }
      },
      fail: (res) => {
        console.log('getSetting-fail', res);
      }
    })
  })
}
function authorize(scope, resolve, reject) {
  wx.authorize({
    scope: key,
    success: (res) => {
      resolve({ isAuth: true })
      console.log('success', res);
    },
    fail: (res) => {
      openSetting(scope, resolve, reject)
      console.log('fail', res);
    }
  })
}

function openSetting(scope, resolve, reject) {
  const content = '请为当前小程序授权' + scopeMap[scope] || ""
  wx.showModal({
    title: "授权",
    content,
    confirmText: "去授权",
    success(res) {
      if (res.confirm) {
        wx.openSetting({
          success: (res) => {
            console.log('openSetting', res);
            const { authSetting } = res
            const isAuth = authSetting[key]
            if (isAuth) {
              resolve({ isAuth })
            } else {
              reject({ isAuth })
            }
          },
          fail: (res) => {
            reject({ isAuth: false })
          }
        })
      } else if (res.cancel) {
        reject({ isAuth: false })
      }
    }
  })
}


export const getSetting = ({ tmplId = "" }) => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        if (tmplId) {
          if (!res.subscriptionsSetting.mainSwitch) {
            reject({ mainSwitch: false })
            return
          }
          const subscriptionRes = res.subscriptionsSetting[tmplId]
          console.log('getSetting', res);
          if (subscriptionRes === "accept") {
            resolve({ auth: true })
          } else {
            reject({ auth: false })
          }
          return
        }
        reject({ auth: false })
      },
      fail: (res) => {
        console.log('getSetting-fail', res);
      }
    })

  })

}

